#include <QCoreApplication>
#include <QCommandLineParser>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QDir>
#include "TrLoader.h"
#include "LogManager.h"
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    
    // 解析命令行参数
    QCommandLineParser parser;
    parser.setApplicationDescription("Contract Loader");
    parser.addHelpOption();
    parser.addVersionOption();
    
    // 添加配置路径选项
    QCommandLineOption configPathOption(QStringList() << "c" << "config-path",
        "Path to configuration files directory", "path");
    parser.addOption(configPathOption);

    // 添加环境选项
    QCommandLineOption envOption(QStringList() << "e" << "env",
        "Environment (simnow/tts24)", "env");
    parser.addOption(envOption);
    
    parser.process(app);
    
    // 获取配置路径和环境
    QString configPath = parser.value(configPathOption);
    QString env = parser.value(envOption).toLower();

    // 如果未指定配置路径，使用默认路径
    if (configPath.isEmpty()) {
        // 获取可执行文件所在目录
        QDir execDir(QCoreApplication::applicationDirPath());
        
        // 尝试找到项目根目录
        while (!execDir.exists("Config") && execDir.cdUp()) {
            // 继续向上查找，直到找到Config目录或到达根目录
        }
        
        if (!execDir.exists("Config")) {
            configPath = "/home/QTradeMaster/Config";
        } else {
            configPath = execDir.absolutePath() + "/Config";
        }
    }

    // 根据环境选择配置目录
    if (!env.isEmpty()) {
        configPath = configPath + "/" + env;
    } else {
        // 如果未指定环境，检查当前工作目录名称
        QDir currentDir = QDir::current();
        QString dirName = currentDir.dirName().toLower();
        if (dirName == "simnow" || dirName == "tts24") {
            configPath = configPath + "/" + dirName;
        } else {
            // 默认使用simnow环境
            configPath = configPath + "/simnow";
        }
    }

    // 确保配置目录存在
    QDir configDir(configPath);
    if (!configDir.exists()) {
        qCritical() << "Config directory does not exist:" << configPath;
        return -1;
    }

    // 初始化日志
    QString logConfigFile = configPath + "/logger.json";
    if (!QFile::exists(logConfigFile)) {
        qCritical() << "Log config file does not exist:" << logConfigFile;
        return -1;
    }

    if (!LOG_MANAGER->init(logConfigFile.toStdString())) {
        qCritical() << "Failed to initialize log manager";
        return -1;
    }
    
    // 读取配置文件
    QString loaderConfigFile = configPath + "/loader.json";
    QFile file(loaderConfigFile);
    if (!file.open(QIODevice::ReadOnly)) {
        MLOG_ERROR("main", "Failed to open config file: {}", loaderConfigFile.toStdString());
        return -1;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        MLOG_ERROR("main", "Failed to parse config file: {}", parseError.errorString().toStdString());
        return -1;
    }

    QJsonObject jsonObj = doc.object();
    QJsonObject ctpConfig = jsonObj["ctp"].toObject();

    // 转换配置到QMap
    QMap<QString, QVariant> conf;
    conf["brokerID"] = ctpConfig["brokerID"].toString();
    conf["userID"] = ctpConfig["userID"].toString();
    conf["password"] = ctpConfig["password"].toString();
    conf["frontAddr"] = ctpConfig["frontAddr"].toString();
    conf["flowPath"] = ctpConfig["flowPath"].toString();
    conf["module"] = ctpConfig["module"].toString();
    conf["appID"] = ctpConfig["appID"].toString();
    conf["authCode"] = ctpConfig["authCode"].toString();
    conf["mapPath"] = ctpConfig["mapPath"].toString();
    conf["contractsPath"] = ctpConfig["contractsPath"].toString();

    MLOG_INFO("main", "Using config path: {}", configPath.toStdString());

    // 创建并启动加载器
    TrLoader loader;
    if (!loader.init(conf)) {
        MLOG_ERROR("main", "Failed to initialize contract loader");
        return -1;
    }

    MLOG_INFO("main", "Contract loader initialized successfully");
    loader.start();
    MLOG_INFO("main", "Contract loader started");
    
    return app.exec();
} 